#include "KeyFrame.h"

KeyFrame::KeyFrame(){
	mX = 0.0f;
	mZ = 0.0f;
	mY = 0.0f;
	mSlerpAmount = 0.0f;
	mTFinal = 0.0f;
	mStart = false;
	mOrigOrientation = new D3DXQUATERNION();
	mQuatOrientation = new D3DXQUATERNION();
	D3DXQuaternionIdentity( mQuatOrientation );
	D3DXQuaternionIdentity( mOrigOrientation );
}
KeyFrame::KeyFrame(float x, float y, float z, D3DVECTOR* rotVect, float w , float TFinal){
	mX = x;
	mZ = z;
	mY = y;
	mTFinal = TFinal;
	mStart = false;
	mSlerpAmount = 0.0f;

	mQuatOrientation = new D3DXQUATERNION();
	D3DXQuaternionIdentity( mQuatOrientation );
	
	mOrigOrientation = new D3DXQUATERNION();
	D3DXQuaternionIdentity( mOrigOrientation );

	
	if(rotVect != NULL){
		::D3DXQuaternionRotationAxis(mQuatOrientation,new D3DXVECTOR3(rotVect->x,rotVect->y,rotVect->z), w);
		D3DXQuaternionNormalize(mQuatOrientation,mQuatOrientation);
		mOrigOrientation = new D3DXQUATERNION();
	}
	else{
		mQuatOrientation = NULL;
	}
	
}

 void KeyFrame::Update(LPDIRECT3DDEVICE9 d3ddev, D3DVECTOR* mModel, D3DVECTOR* pRot, D3DXMATRIX* pRotMatrix, double pElapsedTime, double pTotalTime){
	//Makes sure the Keyframe is still valid
	if(pTotalTime < mTFinal){
		
		if(!mStart){
			mStartTime = pTotalTime;
			//Determines the amount per millisecond to move the object.
			mDelta.x = (mX - mModel->x)/(mTFinal - pTotalTime);
			mDelta.y = (mY - mModel->y)/(mTFinal - pTotalTime);
			mDelta.z = (mZ - mModel->z)/(mTFinal - pTotalTime);
			mStart = true;	
		}

		//Interpolates the position of the object
		mModel->x += (mDelta.x) * pElapsedTime;
		mModel->y += (mDelta.y) * pElapsedTime;
		mModel->z += (mDelta.z) * pElapsedTime;

		if(mQuatOrientation != NULL){

			D3DXQUATERNION mModelQuat;
			
			mSlerpAmount =  pElapsedTime/ (mTFinal - (pTotalTime - pElapsedTime));
			D3DXQUATERNION* mor = mOrigOrientation;
			D3DXQUATERNION* mquat = mQuatOrientation;
			float slerp = mSlerpAmount;

			//::D3DXQuaternionRotationYawPitchRoll(mOrigOrientation,pRot->x,pRot->y,pRot->z);
			::D3DXQuaternionRotationMatrix(mOrigOrientation,pRotMatrix);
			D3DXQuaternionNormalize(mOrigOrientation,mOrigOrientation);
			//Slerps between the quaternions.
			D3DXQuaternionSlerp( &mModelQuat , mOrigOrientation, mQuatOrientation, slerp);
			D3DXQuaternionNormalize(&mModelQuat,&mModelQuat);
			


			//mModelQuat += *mOrigOrientation;
			//::D3DXQuaternionMultiply(&mModelQuat, mOrigOrientation, &mModelQuat);
			//D3DXQuaternionNormalize(&mModelQuat,&mModelQuat);

			D3DXMATRIX* m = new D3DXMATRIX();
			D3DXMatrixRotationQuaternion(pRotMatrix,&mModelQuat);
		}
	}
}
 float KeyFrame::GetTFinal(){
		return mTFinal;
}

